import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:nmb/models/fold.dart';
import 'package:nmb/screens/select_fold.dart';
import 'package:nmb/services/global.dart';
import 'package:nmb/utils/util.dart';
import 'package:path_provider/path_provider.dart';
import '../models/note.dart';
import 'package:intl/intl.dart';

import '../services/database.dart';

class NoteDetailScreen extends StatefulWidget {
  final String? noteId;

  const NoteDetailScreen({super.key, this.noteId});

  @override
  _NoteDetailScreenState createState() => _NoteDetailScreenState();
}

class _NoteDetailScreenState extends State<NoteDetailScreen> {
  final _formKey = GlobalKey<FormState>();
  late Note? note;
  late String title;
  late String content;
  late List<String> tags;
  bool isNewNote = true;
  final ValueNotifier<bool> isEdit = ValueNotifier(false);
  final ValueNotifier<int> contentCnt = ValueNotifier(0);

  late final  TextEditingController _contentCtl;
  late final  TextEditingController _titleCtl;

  final service = Get.find<GlobalService>();
  final dbHelper = Get.find<DatabaseService>();

  Fold? _selectedFold;

  @override
  void initState() {
    super.initState();
    _contentCtl = TextEditingController();
    _titleCtl = TextEditingController();
    _selectedFold = service.foldList[0];
    _contentCtl.addListener((){
      contentCnt.value = _contentCtl.value.text.runes.length;
    });
    note = null;
    if (widget.noteId != null) {
      isEdit.value = false;
      loadNote();
    } else {
      isEdit.value = true;
      title = '';
      _titleCtl.text = '';
      content = '';
      _contentCtl.text = '';
      tags = [];
    }
  }
  Future<void> loadNote() async {
    note = await dbHelper.readNote(widget.noteId!);
    setState(() {
      title = note!.title;
      content = note!.content;
      _titleCtl.text = note!.title;
      _contentCtl.text = note!.content;
      _selectedFold = service.foldList.firstWhereOrNull((e)=>e.id==note!.foldId);
    });
  }

  Future<void> saveNote() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      final now = DateTime.now();
      if (widget.noteId==null) {
        // 子新增
        final newNote = Note(
          title: title,
          content: content,
          dateCreated: now,
          foldId: _selectedFold!.id,
          id: Util.uuid()
        );
        service.createNote(newNote);
      } else {
        /// 修改
        note = note!.copy(
          title: title,
          content: content,
          dateModified: now,
          foldId: _selectedFold!.id,
          id: widget.noteId
        );
        service.updateNote(note!);
      }
      isEdit.value = false;
    }
  }

  Future<void> deleteNote() async {
    if (widget.noteId!=null) {
      await dbHelper.deleteNote(widget.noteId!);
      Navigator.pop(context);
    }
  }

  // 辅助方法
  PopupMenuItem<String> _buildMenuItem(IconData icon, String text, String value) {
    return PopupMenuItem<String>(
      value: value,
      height: 40, // 更接近微信的菜单项高度
      child: Row(
        children: [
          Icon(icon, size: 20),
          const SizedBox(width: 12),
          Text(text,style: TextStyle(
            color: Colors.white
          ),),
        ],
      ),
    );
  }

  Future<void> _handleMenuSelection(Object? value) async {

    switch (value) {
      case 'copy':
        await Clipboard.setData(ClipboardData(text: _contentCtl.text));
        Util.showSimpleAlert(context, '正文复制成功！');
        break;
      case 'edit':
        isEdit.value = true;
        break;
      case 'del':
        deleteNote();
        break;
      case 'export':
        exportTextFile();
        break;
    }
  }

  List<Widget> _genActions(){
    return  [
      ValueListenableBuilder(valueListenable: contentCnt, builder: (context,cnt,child){
        return Text('$cnt字');
      }),
      ValueListenableBuilder(valueListenable: isEdit, builder: (context,edit,child){
        if(edit){
          return IconButton(onPressed: (){
            saveNote().then((val){
            }).onError((e,t){

            });
          }, icon: Icon(Icons.check));
        }else{
         return PopupMenuButton<String>(
            color: Color(0xff242424),
            position: PopupMenuPosition.under,
            icon: Icon(Icons.more_vert_rounded),
            itemBuilder: (context) =>[
              _buildMenuItem(Icons.copy, "复制", "copy"),
              _buildMenuItem(Icons.edit, "修改", "edit"),
              _buildMenuItem(Icons.delete, "删除", "del"),
              _buildMenuItem(Icons.save, "导出", "export"),
            ],
            onSelected: (value)=>_handleMenuSelection(value),
          );
        }
      })
    ];
  }

  Future<void> exportTextFile() async {
    try {
      // 获取存储目录
      final directory = await getExternalStorageDirectory();
      final title = _titleCtl.text;
      final file = File('${directory?.path}/$title.txt');
      final content = _contentCtl.text;
      // 写入文件
      await file.writeAsString(content);
      // 提示用户
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('文件已保存到: ${file.path}'))
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导出失败: $e'))
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black12,
        foregroundColor: Colors.white,
        actions: _genActions()
      ),
      body: Form(
        key: _formKey,
        child: ValueListenableBuilder(valueListenable: isEdit,builder: (context,edit,child){
          return Column(
            children: [
              TextFormField(
                controller: _titleCtl,
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 22,
                    fontWeight: FontWeight.bold
                ),
                cursorColor: Colors.amber,
                decoration: const InputDecoration(
                  border: InputBorder.none,
                  filled: true,
                  hintText: '请输入标题',
                  fillColor: Colors.black,

                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入标题';
                  }
                  return null;
                },
                readOnly: !edit,
                onSaved: (value) => title = value!,
              ),
              if (note!=null)
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(vertical: 8.0,horizontal: 16.0),
                      child: Text(
                        DateFormat('yyyy-MM-dd HH:mm').format(note!.dateCreated),
                        style: const TextStyle(color: Colors.grey),
                      ),
                    ),
                    GestureDetector(
                      onTap: (){
                        if(!edit) return;
                        Get.to(SelectFold())?.then((res){
                          if(res!=null){
                            setState(() {
                              _selectedFold = res;
                            });
                          }
                        });
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(vertical: 8.0,horizontal: 16.0),
                        child: Row(
                          children: [
                            Text(_selectedFold!.name,style: TextStyle(
                              color: edit? Colors.amber:Colors.white,
                              fontSize: 16
                            ),),
                            if(edit)
                            Icon(Icons.arrow_forward_ios_rounded,color: Colors.amber,size: 16,)
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              SizedBox(
                height: 16,
              ),
              Expanded(
                child: TextFormField(
                  cursorColor: Colors.amber,
                  controller: _contentCtl,
                  decoration: const InputDecoration(
                      border:InputBorder.none,
                      alignLabelWithHint: true,
                      filled: true,
                      fillColor: Colors.black,
                      hintText: '请输入内容'
                  ),
                  readOnly: !edit,
                  maxLines: null,
                  expands: true,
                  textAlign: TextAlign.left,
                  textAlignVertical: TextAlignVertical.top,
                  style: TextStyle(
                      color: Colors.white,
                      height: 1.6,
                      fontWeight: FontWeight.normal,
                      fontSize: 18
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入内容';
                    }
                    return null;
                  },
                  onSaved: (value) => content = value!,
                ),
              ),
            ],
          );
        },)
      ),
      backgroundColor: Colors.black,
    );
  }
}